<script setup>

import {Delete, Plus, View} from "@element-plus/icons-vue";
import {onMounted, ref} from "vue";
import {userInfoStore} from "@/stores/userinfo";
import {addFicReq, deleteFicReq, getFictionReq, getCategoryReq, updateFicReq} from "@/api/fiction";
import {userTokenStore} from "@/stores/token";
import {QuillEditor} from "@vueup/vue-quill";
import {ElMessage, ElMessageBox} from "element-plus";
import {logoutReq} from "@/api/user";
import router from "@/router/router";
import WebFictionInfo from "@/views/webFiction/WebFictionInfo.vue";

const userToken = userTokenStore()

//获得query参数
const urlMana = window.location.href
console.log("urlaaa:" + urlMana)
const categoryId =ref( urlMana.split("=")[1])
console.log("caaa:" + categoryId.value)
const cId=categoryId.value

if(categoryId.value===undefined){
  categoryId.value=''
}


const fictions = ref()

const categories = ref()

//抽屉开关
const showDrawer = ref(false)
//抽屉开关2
const showDrawer2 = ref(false)
//抽屉的标题
const drawerTitle = ref('新增小说')
//抽屉的标题2
const drawerTitle2 = ref('小说简介')

//用户获取当前的小说的简介
const introduction = ref('')
const fictionTitle = ref('')



//小说表单
const fictionModel = ref({
    title: '',
    categoryId: '',
    coverImage: '',
    author: '',
    introduction: '<p></p>',
    id: '',
})

//查询参数
const params = ref({
    pageNum: 1,
    pageSize: 5,
    categoryId: categoryId.value,

})
const total = ref(0)

const currentName=ref('')

//获取小说列表
const getFictionList = async () => {

  console.log(params.value)
    let result = await getFictionReq(params.value);
    //获取小说分类
    let cresult = await getCategoryReq()
    categories.value = cresult.data
    fictions.value = result.data.data
    console.log(fictions.value)
    //设置小说列表扩展小说分类名字段
    for (let i = 0; i < fictions.value.length; i++) {
        let art = fictions.value[i];
        for (let j = 0; j < categories.value.length; j++) {
            //通过分类id CategoryId 与 小说分类id匹配
            if (art.categoryId === categories.value[j].id) {
                //扩展字段
                art.categoryName = categories.value[j].categoryName
              currentName.value=categories.value[j].categoryName

            }
        }
    }
    //设置总条数
    total.value = result.data.total

}

const beforeUpload = () => {
    return {'fileType': 0}
}
//回显图片
const handleSuccess = (resp) => {
    fictionModel.value.coverImage = resp.data
}

//清空模型数据
const clearModel = () => {
    fictionModel.value.id = ''
    fictionModel.value.title = ''
    fictionModel.value.author = ''
    fictionModel.value.introduction = '<p></p>'
    fictionModel.value.coverImage = ''
    fictionModel.value.categoryId = ''
}

//添加小说
const add = async () => {
    //发送请求
    let result = await addFicReq(fictionModel.value)
    ElMessage.success(result.message)
    //关闭抽屉
    showDrawer.value = false
    //刷新表格
    await getFictionList()
}

//修改操作
const edit = (rowData) => {
    drawerTitle.value = '修改小说'
    //模型赋值
    fictionModel.value.id = rowData.id
    fictionModel.value.title = rowData.title
    fictionModel.value.introduction = rowData.introduction
    fictionModel.value.coverImage = rowData.coverImage
    fictionModel.value.categoryId = rowData.categoryId
    fictionModel.value.author = rowData.author
    fictionModel.value.titleUrl = rowData.titleUrl

  console.log(fictionModel.value)
    //打开抽屉
    showDrawer.value = true
}
//修改小说
const update = async () => {
    let result = await updateFicReq(fictionModel.value)
    ElMessage.success(result.message)

    showDrawer.value = false

    await getFictionList()
    clearModel()
}
//提交修改
const submit =async () => {
    if (drawerTitle.value == '新增小说') {
        await add()
    } else {
        await update()
    }
}
//删除小说
const deleteFic = (rowData) => {
    ElMessageBox.confirm(
        '确认要删除【ID】=' + rowData.id + '吗',
        '温馨提醒',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            console.log("发送删除请求:" + rowData.id)
            let result = await deleteFicReq(rowData.id);
            ElMessage.success(result.message)
            getFictionList()
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除取消',
            })
        })
}
//改变每页显示多少条数据的方法
const handleSizeChange = (size) => {
    //改变每页显示的数据量
    params.value.pageSize = size
    //重新获取数据
    getFictionList()
}
//点击具体页码触发函数
const handleCurrentChange = (pageNum) => {
    params.value.pageNum = pageNum
    getFictionList()
}
//查看小说详情
const detail = (rowDate) => {
    showDrawer2.value = true;
    fictionTitle.value = rowDate.title
    introduction.value = rowDate.introduction
}
//获取小说详情，并导航到小说详情页面
const showInfo = (url) => {
    router.push({ path: `/webFictionInfo`, query: { titleUrl: url } });
};
onMounted(() => {
    getFictionList()
})
</script>
<template>
    <el-card class="card-container">
        <template #header>
            <div class="card-header">
                <span v-if="categoryId===''">我的全部小说</span>
                <span v-else>{{currentName}}</span>
            </div>

        </template>
        <!--    使用表格组件展示小说列表
        查询小说 多条件查询
        修改小说
        删除小说
        -->
        <el-table :data="fictions">
            <el-table-column prop="id" label="ID" width="70"/>
            <el-table-column prop="title" label="小说标题" width="200">
                <template #default="scope">
                    <a href="javascript:void(0)" @click="() => showInfo(scope.row.titleUrl)">
                        {{ scope.row.title }}
                    </a>
                </template>
            </el-table-column>
            <el-table-column prop="author" label="作者"/>
            <el-table-column label="封面预览">
                <template #default="{row}">
                    <el-image class="avatar" :src="row.coverImage"/>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间"/>
            <el-table-column prop="updateTime" label="修改时间"/>
            <el-table-column fixed="right" label="操作" width="200">
                <template #default="{row}">
                    <el-button :icon="Plus" link type="warning" size="small" @click="edit(row)">修改</el-button>
                    <el-button :icon="Delete" link type="danger" size="small" @click="deleteFic(row)">删除</el-button>
                    <el-button :icon="View" link type="primary" size="small" @click="detail(row)">简介</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            class="pagination"
            v-model:current-page="params.pageNum"
            v-model:page-size="params.pageSize"
            :page-sizes="[1, 2, 3, 4, 5, 10]"
            :disabled="disabled"
            :background="background"
            layout="sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </el-card>
    <!-- 抽屉（修改小说） -->
    <el-drawer class="drawer" v-model="showDrawer" :title="drawerTitle" append-to-body lock-scroll="false" direction="rtl" size="40%">
        <el-form :model="fictionModel" label-width="100px">
            <el-form-item label="小说标题">
                <el-input v-model="fictionModel.title"></el-input>
            </el-form-item>
            <el-form-item label="小说分类">
                <!--        选择分类下拉框-->
                <el-select v-model="fictionModel.categoryId" placeholder="请选择分类">
                    <el-option v-for="item in categories" :key="item.id" :label="item.categoryName" :value="item.id"/>
                </el-select>
            </el-form-item>
            <!--      小说封面-->
            <el-form-item label="小说封面">
                <el-upload
                    class="avatar-uploader"
                    :data="beforeUpload"
                    action="http://localhost:8080/upload"
                    :show-file-list="false"
                    :headers="{'token':userToken.getToken()}"
                    :on-success="handleSuccess"
                >
                    <img v-if="fictionModel.coverImage" :src="fictionModel.coverImage" width="320" height="180"/>
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus/>
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="作者">
                <el-input v-model="fictionModel.author"></el-input>
            </el-form-item>
            <!--      小说简介 富文本-->
            <el-form-item label="小说简介">
                <div class="content-edit">
                    <textarea v-model="fictionModel.introduction"></textarea>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submit()">提交</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>

    <!-- 抽屉（查看小说详情） -->
    <el-drawer class="drawer" v-model="showDrawer2" :title="drawerTitle2" append-to-body lock-scroll="false" direction="rtl" size="30%">
        <div class="introduction-container">
            <h4 class="introduction-title" v-html="fictionTitle"></h4>
            <hr style="color:gray;">
            <div class="introduction-content" v-html="introduction"></div>
        </div>
    </el-drawer>


</template>

<style scoped>
@import '@/assets/base.css';
.content-edit textarea{
    width: 450px;
  height:200px;
}

:deep(.ql-editor) {
    min-height: 200px;
    width: 100%;
}

.avatar {
    width: auto;
    height: auto;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.avatar-uploader {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.introduction-container {
    padding: 20px;
    background-color: #f9f9f9;
}

.introduction-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: center;
    color: gray;
}
.introduction-content {
    margin-top: 20px;
    text-align: justify;
    line-height: 1.6;
    font-size: 16px;
    color: gray;
}


</style>